package top.ffhome.security.securityspringboot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.ffhome.security.securityspringboot.dao.UserDao;
import top.ffhome.security.securityspringboot.model.UserDto;

@Slf4j
@Service
public class SpringDataUserDetailsService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto user = userDao.getUserByUsername(username);
        log.info("user:{}", user);
        if (user == null) {
            return null;
        }

        return User.withUsername(user.getUsername()).password(user.getPassword())
                .authorities(userDao.findPermissionsByUserId(user.getId())).build();
    }
}
